import React from "react";
import {
  ConfigProvider,
  DatePicker,
  Alert,
  Input,
  Button,
  List,
  Row,
  Col,
  Drawer
} from "antd";
import { CHANGE_INPUT, REMOVE, ADD } from "../../store/actionTypes";
import store from "../../store";
import zhCN from "antd/es/locale/zh_CN";
import NavTabLeft from "../../component/tabbar.jsx";
// exceljs
import Excel from "exceljs";
import * as FileSave from "file-saver";
import base64 from "STATIC/js/base64";
import { cityMess, postFun, http } from "../../http/postArr";
const qs = require("qs");
var workbook = new Excel.Workbook();
require("./login.scss");
const EXCEL_TYPE =
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8";

class LoginIndex extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      date: new Date(),
      List: store.getState(),
      visible: false,
      open: false,
      routerRef: React.createRef
    };
    this.alertdom = React.createRef();
    this.changeValue = this.changeValue.bind(this);
    this.storeChange = this.storeChange.bind(this);
    this.add = this.add.bind(this);
    store.subscribe(this.storeChange);
  }
  showDrawer = () => {
    this.setState({
      visible: true
    });
  };
  onClose = () => {
    this.setState({
      visible: false
    });
  };
  render(h) {
    const filterTime = date => {
      if (date != null) {
        return date.getTime();
      } else {
        return "暂无信息";
      }
    };
    return (
      <div>
        <Alert message="Success Text" type="success" />
        <p id="baseImg"></p>
        <Button
          type="primary"
          icon="desktop"
          onClick={this.showDrawer}
        ></Button>
        <NavTabLeft activeIndex={1}>
          <solt-p>
            <div ref={this.state.routerRef}>WDNMDHKJ</div>
          </solt-p>
        </NavTabLeft>
        <ConfigProvider locale={zhCN}>
          <div style={{ width: 400, boxShadow: "2px 1px 0px 1px" }}>
            <DatePicker onChange={this.handleChange} />
          </div>
        </ConfigProvider>
        <div
          onClick={this.alertClick}
          ref={this.alertdom}
          style={{ marginTop: 20, textAlign: "right" }}
          className={`backGround`}
        >
          {filterTime(this.state.date)}
        </div>
        <input type="file" onChange={this.xlsxClick.bind(this)} />
        <Input
          value={this.state.List.inputValue}
          onChange={this.changeValue}
          placeholder={this.state.List.inputValue}
          style={{ width: "200px" }}
        />
        <Button type="primary" onClick={this.add}>
          增加
        </Button>
        <List
          bordered
          dataSource={this.state.List.list}
          renderItem={(item, index) => (
            <Row align="middle" justify="center" type="flex">
              <Col span={12}>{item}</Col>
              <Col className={`flex center`} span={12}>
                <Button
                  onClick={this.removeList.bind(this, index)}
                  type="primary"
                  shape="circle"
                  icon="close"
                ></Button>
              </Col>
            </Row>
          )}
        />
        <Drawer
          title="WDNMD"
          placement="bottom"
          closable={false}
          onClose={this.onClose}
          visible={this.state.visible}
        >
          <p>Some contents...</p>
        </Drawer>
        <Button onClick={this.exportExcel.bind(this)}>导出excel</Button>
        <button
          onClick={this.menuCLick.bind(this)}
          className={`menu ${this.state.open ? "active" : ""}`}
        >
          <svg viewBox="0 0 64 48">
            <path d="M19,15 L45,15 C70,15 58,-2 49.0177126,7 L19,37"></path>
            <path d="M19,24 L45,24 C61.2371586,24 57,49 41,33 L32,24"></path>
            <path d="M45,33 L19,33 C-8,33 6,-2 22,14 L45,37"></path>
          </svg>
        </button>
      </div>
    );
  }
  handleChange = date => {
    this.setState({
      date: date == null ? null : date["_d"]
    });
    this["postData"](this["state"]["date"]);
  };
  postData = e => {
    console.log(e);
  };
  alertClick = e => {
    console.log(this.alertdom);
  };
  removeList(e) {
    const action = {
      type: REMOVE,
      index: e
    };
    store.dispatch(action);
  }
  changeValue(e) {
    const action = {
      type: CHANGE_INPUT,
      value: e.target.value
    };
    store.dispatch(action);
  }
  storeChange() {
    this.setState({
      List: store.getState()
    });
  }
  add() {
    // 通过引入全部changeAction
    const action = {
      type: ADD
    };
    store.dispatch(action);
  }
  componentDidMount() {
    // node开启本地服务
    // http({
    //   baseURL:"http://localhost:8077"
    // })

    // 获取从 /main 路由穿过来的数据
    // console.log(this.props.location.state);
    // symbol 定义Symbol 两值不等
    // let sy_y_f = Symbol("aa bb"),
    //   sy_y_s = Symbol("aa bb");
    // window.localStorage.setItem("token",'saaaaaaansajn')
    // window.localStorage.removeItem("key");
    // 本地持久化存储
    // let arr = [undefined, null, 2, 5, 4, 3, 1];
    // let a = this["quickSort"](arr);
    // 输出为 [null, 1, 2, 3, 4, 5, undefined];

    // cityMess().then(res => {
    //   console.log(res,'cityMess');
    // });

    // 获取网络图片base64编码

    // this.getBase64("https://pic1.zhimg.com/v2-1f93f4550bc5b355c8da9ad755aaf434_is.jpg");
    // this.Say("HKJ").then(res=>{
    //   console.log(res);
    // })
  }
  // promise函数
  MyName(name) {
    return new Promise(function(res, rej) {
      rej("cuowu");
      // res("WDNMD"+name);
    });
  }
  // async 函数
  async Say(name) {
    let _const = this;
    try {
      const n = await _const.MyName(name);
      return n;
    } catch (err) {
      console.log(err+"err");
      return err;
    }
  }
  // 快速排序 null 在前 undefind 在最后
  quickSort(arr) {
    if (arr.length <= 1) return arr;
    let pivotIndex = Math.floor(arr.length / 2),
      pivot = arr.splice(pivotIndex, 1)[0],
      smallArr = [],
      bigArr = [];
    arr.foreach((item, index) => {
      if (item < pivot) {
        smallArr.push(item);
      } else bigArr.push(item);
    });
    return this.quickSort(smallArr).concat([pivot], this.quickSort(bigArr));
  }
  // 导出excel
  exportExcel() {
    var fills = {
      solid: {
        type: "pattern",
        pattern: "solid",
        fgColor: { argb: "FFFFAAAA" }
      }
    };

    //create a workbook
    //add header
    var ws1 = workbook.addWorksheet("测试一");
    ws1.addRow(["地址", "地面"]);
    ws1.addRow(["总人口", "不可计数"]);
    ws1.addRow(["类型", "动物", "非动物"]);
    ws1.addRow(["统计日期", "1111-11-11 11:11:11"]);
    ws1.addRow();

    //A6:E6
    ws1.addRow(["你", "在", "说些", "神马", "呢？"]);
    ws1.getCell("A6").fill = fills.solid;
    ws1.getCell("B6").fill = fills.solid;
    ws1.getCell("C6").fill = fills.solid;
    ws1.getCell("D6").fill = fills.solid;
    ws1.getCell("E6").fill = fills.solid;

    //7 - 13(A7:A13) - 7
    ws1.addRow(["什么跟神马", 10, 1, "凡人修仙传", 7]);
    ws1.addRow(["", "", "", "一号遗迹", 2]);
    ws1.addRow(["", "", "", "六号遗迹", 0]);
    ws1.addRow(["", "", "", "古国一号", 0]);
    ws1.addRow(["", "", "", "锻体期", 0]);
    ws1.addRow(["", "", "", "合体期", 0]);
    ws1.addRow(["", "", "", "没资质", 1]);

    ws1.mergeCells("A7:A13");
    ws1.mergeCells("B7:B13");
    ws1.mergeCells("C7:C13");

    //a6-e13 a b c d e
    ws1.getCell("A7").alignment = { vertical: "middle", horizontal: "center" };
    var ws2 = workbook.addWorksheet("测试二");
    var ws3 = workbook.addWorksheet("测试三");
    //
    // return false;
    let url =
      "https://pic1.zhimg.com/v2-1f93f4550bc5b355c8da9ad755aaf434_is.jpg";
    base64(url).then(
      function(res) {
        var baseData = res;
        var imgId = workbook.addImage({
          base64: baseData,
          extension: "png"
        });
        ws1.addImage(imgId, {
          tl: { col: 5, row: 3 },
          ext: { width: 100, height: 200 }
        });

        workbook.xlsx.writeBuffer().then(res => {
          const blob = new Blob([res], { type: EXCEL_TYPE });
          FileSave.saveAs(blob, "下载.xlsx");
        });
      },
      function(err) {
        console.log(err); //打印异常信息
      }
    );
  }
  xlsxClick(e) {
    console.log(e);
  }
  menuCLick(e) {
    this.setState({
      open: !this.state.open
    });
  }
  // 通过xhr获取图片base64编码
  getBase64(URL) {
    let _const = this,
      xhr = new XMLHttpRequest(),
      base64 = new String();
    window.URL = window.URL | window.webkitURL;
    xhr.open("get", URL, true);
    xhr.responseType = "blob";
    xhr.onload = function() {
      if (this.status == 200) {
        //得到一个blob对象
        let blob = this.response;
        // 至关重要
        let oFileReader = new FileReader();
        oFileReader.onload = function(e) {
          base64 = e.target.result;
          console.log(base64, "base64");
          return base64;
        };
        oFileReader.readAsDataURL(blob);
        // //====为了在页面显示图片，可以删除====
        // let img = document.createElement("img");
        // img.onload = function(e) {
        //   window.URL.revokeObjectURL(img.src); // 清除释放
        // };
        // console.log(window,'url');
        // let src = window.URL.createObjectURL(blob);
        // img.src = src;
        // document.getElementById("baseImg").appendChild(img);
        // //====为了在页面显示图片，可以删除====
      }
    };
    xhr.send();
  }
  componentWillReceiveProps(newProps) {
    console.log(newProps);
  }
}
export default LoginIndex;
